<template>
    <basic-container>
        <el-form ref="form" :rules="rules" :model="form" label-width="100px" style="background-color:#fefefe;">
            <el-form-item label="发送对象:" prop="userType">
                <el-radio-group v-model="form.userType" @change="radioChange">
                    <el-row style="padding: 5px">
                        <el-radio :label="0">所有会员</el-radio>
                    </el-row>
                    <el-row style="padding: 5px">
                        <el-radio :label="1" >指定会员</el-radio>
						<el-button v-if="form.userType==1" type="primary"  size="mini"  @click="changeUser">修改指定会员</el-button>
                    </el-row>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="标题" prop="title">
                <el-input style="width: 50%;padding-right:40px;" type="textarea" maxlength="100" show-word-limit :autosize="{ minRows: 2, maxRows: 6}" v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item label="通知内容" prop="content">
                <el-input style="width: 50%;padding-right:40px" type="textarea" maxlength="100" show-word-limit :autosize="{ minRows: 2, maxRows: 6}"
                          v-model="form.content"></el-input>
            </el-form-item>
            <el-form-item style="display: flex;justify-content: center;width: 60%">
                <el-button type="primary" :disabled="disabled" @click="onSubmit">立即发送</el-button>
                <el-button @click="onCancle">取消</el-button>
            </el-form-item>
        </el-form>
        <avue-crud :data="data" :option="option" v-model="obj" :page="page"
                   @refresh-change="refreshChange"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @current-change="currentChange"
                   @size-change="sizeChange" @on-load="onLoad">
            <template slot-scope="{row}" slot="content">
                <el-tooltip class="item" effect="dark" :enterable="false" :content="row.content" placement="top-start">
                    <span>{{row.content}}</span>
                </el-tooltip>
            </template>
        </avue-crud>
        <!--        选择发送范围-->
        <el-drawer
                title="选择发送对象"
                :visible.sync="sendDrawer"
                size="75%"
                direction="rtl"
				:show-close="false"
				:wrapperClosable="false"
                :before-close="cancleChoose">
            <el-row>
                <el-col :span="18">
                    <avue-crud ref="sendRef" :data="dataSend" :option="optionSend" v-model="objSend" :page="pageSend"
                               @refresh-change="refreshChangeSend"
                               @search-change="searchChangeSend"
                               @search-reset="searchResetSend"
                               @current-change="currentChangeSend"
                               @size-change="sizeChangeSend" >
                        <template slot-scope="{row}" slot="add">
                            <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="addChooseItem(row)"></el-button>
                        </template>
                    </avue-crud>
                    <div style="display: flex;justify-content: center">
                        <el-button type="primary"  size="mini" :disabled="disChioce"  @click="submitChoose">保存</el-button>
                        <el-button  size="mini"  @click="cancleChoose">取消</el-button>
                    </div>
                </el-col>
                <el-col :span="6">
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>已选会员列表</span>
                        </div>
                        <div v-for="item in chooseList" :key="item.id" class="text item">
                            <span>{{item.name }}</span>
                            <el-button style="float: right; padding: 3px 0" type="text" @click="removeChooseItem(item)">删除</el-button>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

        </el-drawer>
    </basic-container>
</template>
<script>
    import {sendMsgToBuyers,getBuysByPhone,getMsgToBuyers} from '@/api/admin/sysMessage.js'
    import userType from "../../base/member/userType";

    export default {
        data() {
            return {
                chooseList:[], // 已选中会员列表
				disChioce:false,
				disabled:false,
                chooseArr:[],
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() + 3600 * 1000 * 24 * 1 < Date.now();
                    },
                },
                couponEndTime: "",
                couponBeginTime: "",
                sendDrawer: false,
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                pageSend: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                querySend:{},
                query:{},
                form: {
                    userType: 0,
                    content: '',
                    title: ''
                },
                rules: {
                    userType: [
                        {required: true, message: '请选择发送对象', trigger: 'change'}
                    ],
                    content: [
                        {required: true, message: '请输入内容', trigger: 'blur'},
                        {max: 100, message: '输入长度不得多于100个长度', trigger: 'blur'},

                    ],
                    title: [
                        {required: true, message: '请填写标题', trigger: 'blur'},
                        {max: 100, message: '输入长度不得多于100个长度', trigger: 'blur'},
                    ]
                },
                obj: {},
                data: [],
                option: {
                    // expand: true,
                    menu:false,
                    addBtn: false,
                    title: '发送记录',
                    page: false,
                    align: 'center',
                    menuAlign: 'center',
                    labelWidth: 140,
                    viewBtn: false,
                    delBtn: false,
                    border: true,
                    menuWidth: 300,
                    treeProps: {
                        children: "childrenNodes"
                    },
                    column: [
                        {
                            label: '发送时间',
                            prop: 'addTime',
                            row: true,
                            width:180,
                        },
                        {
                            label: '发送内容',
                            prop: 'content',
                            row: true,
                            slot:true,
                        },
                        {
                            label: '发送对象',
                            prop: 'phone',
                            row: true,
                            width:140,
                        }
                    ]
                },
                objSend: {},
                dataSend: [],
                optionSend: {
                    selection:false,
                    menu: false,
                    addBtn: false,
                    title: '',
                    page: false,
                    align: 'center',
                    menuAlign: 'center',
                    labelWidth: 200,
                    viewBtn: false,
                    delBtn: false,
                    border: true,
                    menuWidth: 300,
                    column: [
                        {
                            label: '',
                            prop: 'add',
                            row: true,
                            slot:true,
                            width:80,
                        },
                        {
                            label: '会员名称',
                            prop: 'name',
                            row: true,
                        },
                        {
                            label: '会员手机号',
                            prop: 'phone',
                            search:true,
                            searchLabelWidth:100,
                            searchSpan:8,
                        },
                        // {
                        //     label: '发送时间',
                        //     prop: 'createTime',
                        //     row: true,
                        // }
                    ]
                },
            }
        },
        created() {
			this.onLoadSend(this.pageSend)
        },
        watch:{
            'chooseList'(){
                if(this.chooseList.length>0) {
                    let chooseArr = []
                    this.chooseList.forEach(item=>{
                        chooseArr.push(item.userId)
                    })
                    this.chooseArr = chooseArr
                }
            }
        },
        methods: {
            onCancle() {
                this.chooseList = []
                this.chooseArr = [] // 点击取消,清空选中的对象
                this.$refs["form"].clearValidate()
                this.$refs["form"].resetFields()
                this.disabled = false
            },
            changeUser(){
                // this.chooseArr = []
                // this.onLoadSend(this.pageSend)
                console.log('chooseList changeUser',this.chooseList)
                this.sendDrawer = true
            },
            // 单选change事件
            radioChange(value) {
                console.log('value', value)
                if (value == 1) {
                    this.sendDrawer = true
                    this.onLoadSend(this.pageSend)
                } else {
                    this.sendDrawer = false
                }
            },
            //搜索时间范围限制
            getTime() {
                if (this.couponBeginTime > this.couponEndTime && this.couponBeginTime && this.couponEndTime) {
                    this.$message({
                        type: "error",
                        message: "结束时间不能小于开始时间"
                    });
                    this.couponEndTime = ''
                }
            },
            onSubmit() {
				this.disabled=true
                console.log('form', this.form)
                if(this.chooseArr.length<1&&this.form.userType==1) {
                    this.$message({
                        type: "error",
                        message: "至少选择一位会员"
                    });
					this.disabled=false
                    return
                }
                if(this.form.title.trim().length<1) {
                    this.$message({
                        type: "error",
                        message: "请输入标题"
                    });
					this.disabled=false
                    return
                }
                if(this.form.content.trim().length<1) {
                    this.$message({
                        type: "error",
                        message: "请输入内容"
                    });
					this.disabled=false
                    return
                }
                this.sendMsgToBuyersFn()
            },
            // 点击页数
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
                this.onLoad(this.page,this.query)
            },
            currentChangeSend(currentPage) {
                this.pageSend.currentPage = currentPage;
                this.onLoadSend(this.pageSend,this.querySend)

            },
            // 点击页数
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
                this.onLoad(this.page,this.query)
            },
            sizeChangeSend(pageSize) {
                this.pageSend.pageSize = pageSize;
                this.onLoadSend(this.pageSend,this.querySend)
            },
            onLoad(page, params = {}, done) {//页面初始化请求管理员列表
                getMsgToBuyers(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    if (done) {
                        done();
                    }
                    this.data = res.data.data
                    this.page.total = res.data.count
                })
            },

            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchResetSend() {
                this.querySend = {};
                this.couponEndTime = ''
                this.couponBeginTime = ''
                this.onLoadSend(this.pageSend);
            },
            // 搜索框
            searchChange(params, done) {
                this.page.currentPage = 1
                this.query = params;
                this.onLoad(this.page, params, done);
            },
            searchChangeSend(params, done) {
                this.pageSend.currentPage = 1
                params.beginTime = this.couponBeginTime
                params.endTime = this.couponEndTime
                this.querySend = params;
                this.onLoadSend(this.pageSend, this.querySend, done);
            },
            refreshChange({page, searchForm}) {
                this.onLoad(this.page);
            },
            refreshChangeSend({page, searchForm}) {
                this.onLoadSend(this.pageSend);
            },
            // 删除已选会员
            removeChooseItem(item) {
                let index = this.chooseList.indexOf(item)
                this.chooseList.splice(index,1)
            },
            // 添加指定会员
            addChooseItem(item) {
                let flag = this.chooseList.some(res=>{
                    return res.userId==item.userId
                })
                if(flag) {
                    this.$message({
                        message: '该对象已选择',
                        type: 'warning'
                    });
                    return
                }
                let arr = [...this.chooseList,item]
                let setObj = new Set(arr)
                this.chooseList = [...setObj]
            },
            submitChoose() {
				this.disChioce=true
                if(this.chooseArr.length<1) {
                    this.$message({
                        message: '请选择发送对象',
                        type: 'error'
                    });
					this.disChioce=false
                    return
                }
				this.disChioce=false
                this.sendDrawer=false
                this.querySend={}
                this.$refs.sendRef.searchReset();
            },
            cancleChoose() {
                this.form.userType=0
                this.sendDrawer=false
                this.querySend={}
				this.chooseList = []
                this.chooseArr = []
				this.$refs.sendRef.searchReset();
            },
            sendMsgToBuyersFn() {
				this.disabled=true
				let data=[]
				if(this.chooseArr.length>0&&this.form.userType==1){
					data=this.chooseArr
				}else{
					data=0
				}
                let obj = {
                    content: this.form.content,
                    title: this.form.title,
                    userId: data
                }
                sendMsgToBuyers(obj).then(res => {
                    this.chooseList = []
                    this.chooseArr = [] // 点击发送,清空选中的对象
                    if (res.data.code == 200) {
                        this.$message({
                            type: "success",
                            message: "添加成功"
                        });
                    }
					this.disabled=false
                    this.$refs.form.resetFields()
                    this.onLoad(this.page)
                })
            },
            // 获取发送对象的
            onLoadSend(page, params = {}, done) {
                getBuysByPhone(page.currentPage, page.pageSize, Object.assign(params, this.querySend)).then(res => {
                    if (done) {
                        done();
                    }
                    this.dataSend = res.data.data
                    this.pageSend.total = res.data.count
                })
            },
        }
    }
</script>
<style lang="scss">
.box-card {
    margin-top: 60px;
}
.box-card .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>
